package com.todo.controller;

import com.todo.common.Result;
import com.todo.dto.LoginRequest;
import com.todo.entity.User;
import com.todo.service.UserService;
import com.todo.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import javax.validation.constraints.Pattern;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtil jwtUtil;

    /**
     * 发送短信验证码
     */
    @PostMapping("/send-code")
    public Result<String> sendCode(@RequestParam @Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确") String phone) {
        try {
            userService.sendSmsCode(phone);
            return Result.success("验证码发送成功");
        } catch (Exception e) {
            log.error("发送验证码失败", e);
            return Result.error("发送验证码失败");
        }
    }

    /**
     * 手机号验证码登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@Valid @RequestBody LoginRequest request) {
        try {
            String token = userService.login(request);
            User user = userService.getUserByPhone(request.getPhone());
            
            Map<String, Object> data = new HashMap<>();
            data.put("token", token);
            data.put("user", user);
            
            return Result.success("登录成功", data);
        } catch (Exception e) {
            log.error("登录失败", e);
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取当前用户信息
     */
    @GetMapping("/info")
    public Result<User> getUserInfo(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            User user = userService.getUserById(userId);
            return Result.success(user);
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return Result.error("获取用户信息失败");
        }
    }

    /**
     * 更新用户信息
     */
    @PutMapping("/info")
    public Result<String> updateUserInfo(@RequestBody User userInfo, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            User user = userService.getUserById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 只允许更新昵称和头像
            user.setNickname(userInfo.getNickname());
            user.setAvatar(userInfo.getAvatar());
            userService.updateUser(user);
            
            return Result.success("更新成功");
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return Result.error("更新用户信息失败");
        }
    }

    /**
     * 更新用户个人资料
     */
    @PutMapping("/profile")
    public Result<User> updateUserProfile(@RequestBody User userInfo, HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            User user = userService.getUserById(userId);
            if (user == null) {
                return Result.error("用户不存在");
            }
            
            // 更新个人资料信息
            if (userInfo.getNickname() != null) {
                user.setNickname(userInfo.getNickname());
            }
            if (userInfo.getEmail() != null) {
                user.setEmail(userInfo.getEmail());
            }
            if (userInfo.getBio() != null) {
                user.setBio(userInfo.getBio());
            }
            if (userInfo.getAvatar() != null) {
                user.setAvatar(userInfo.getAvatar());
            }
            
            userService.updateUser(user);
            
            return Result.success("个人资料更新成功", user);
        } catch (Exception e) {
            log.error("更新个人资料失败", e);
            return Result.error("更新个人资料失败");
        }
    }

    /**
     * 获取用户统计数据
     */
    @GetMapping("/stats")
    public Result<Map<String, Object>> getUserStats(HttpServletRequest request) {
        try {
            Long userId = getUserIdFromRequest(request);
            Map<String, Object> stats = userService.getUserStats(userId);
            return Result.success(stats);
        } catch (Exception e) {
            log.error("获取用户统计失败", e);
            return Result.error("获取用户统计失败");
        }
    }

    /**
     * 从请求中获取用户ID
     */
    private Long getUserIdFromRequest(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            return jwtUtil.getUserIdFromToken(token);
        }
        throw new RuntimeException("未授权访问");
    }
} 